package com.yingwei.${pojo.getMetaAsString("project_name")}.swing;

<#assign hasSet = false >

<#foreach field in pojo.getAllPropertiesIterator()>
<#if pojo.getJavaTypeName(field,false).equals("Set")>
	<#assign hasSet = true >
	<#assign SetClassName = pojo.beanCapitalize(field.name) >
	<#assign field1 = field >
</#if>
</#foreach>

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.InputVerifier;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SpringLayout;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yingwei.${pojo.getMetaAsString("project_name")}.control.Data;
import com.yingwei.${pojo.getMetaAsString("project_name")}.model.businessobject.${pojo.getDeclarationName()};
<#foreach field in pojo.getAllPropertiesIterator()>
<#if (field.type.toString().indexOf("ManyToOneType") > 0) >
import com.yingwei.${pojo.getMetaAsString("project_name")}.model.businessobject.${pojo.getJavaTypeName(field,false)};
</#if>
</#foreach>
import com.yingwei.util.SpringUtilities;

@SuppressWarnings("serial")
/**
 * This class needs to access message bundle properties:
 * add_new_${pojo.getDeclarationName()}, delete_${pojo.getDeclarationName()}, refresh_${pojo.getDeclarationName()}
 * ${pojo.getDeclarationName()}_management
 * 
 */
public class ${pojo.getDeclarationName()}AddEdit extends JPanel
{
    private static Logger logger = LoggerFactory.getLogger(${pojo.getDeclarationName()}AddEdit.class);
    private static Locale currentLocale = Locale.CHINA;
    private static ResourceBundle bundle = ResourceBundle.getBundle("MessagesBundle", Locale.CHINA);
    Data data;
    final JPanel callingPanel;
    final ${pojo.getDeclarationName()} _${pojo.getDeclarationName()};

<#foreach field in pojo.getAllPropertiesIterator()>
<#if !pojo.getJavaTypeName(field,false).equals("Set") >
	<#if pojo.getFieldDescription(field).indexOf("editable") != -1 >
		JTextField ${field.name} = new JTextField(23);
	</#if>	
	<#if (field.type.toString().indexOf("ManyToOneType") > 0) >
		JComboBox ${field.name}ComboBox = new JComboBox();
	</#if>
</#if> 
</#foreach>			 

    public ${pojo.getDeclarationName()}AddEdit(final JPanel callingPanel, final ${pojo.getDeclarationName()} _${pojo.getDeclarationName()})
    {
		super(new BorderLayout());
		setPreferredSize(new Dimension(1200, 800));

		data = Data.getData();
	
		this.callingPanel = callingPanel;
		this._${pojo.getDeclarationName()} = _${pojo.getDeclarationName()};

		JPanel pUpper = new JPanel();
		pUpper.setLayout(new SpringLayout());

	//	pUpper.add(new JLabel("Expiration Date:"));
		//Date today = new Date();
		// Start the spinner today, but don't set a min or max date
		// The increment should be a month
		/*
		//s = new JSpinner(new SpinnerDateModel(today, null, null,
			//Calendar.DAY_OF_MONTH));
		//JSpinner.DateEditor de = new JSpinner.DateEditor(s, "yyyy/MM/dd");
		s.setEditor(de);
		pUpper.add(s);*/

<#assign x = 0> 			
<#foreach field in pojo.getAllPropertiesIterator()>
<#if !pojo.getJavaTypeName(field,false).equals("Set") >
	<#if pojo.getFieldDescription(field).indexOf("editable") != -1 >
		JLabel label_${field.name} = new JLabel("${field.name}", JLabel.TRAILING);
		pUpper.add(label_${field.name});

    if( _${pojo.getDeclarationName()}.${pojo.getGetterSignature(field)}() != null )
        ${field.name}.setText(_${pojo.getDeclarationName()}.${pojo.getGetterSignature(field)}().toString());
		
<#if pojo.getFieldDescription(field).indexOf("pattern=") != -1 >
<#assign pos1 = pojo.getFieldDescription(field).indexOf("pattern=") />
<#assign pos2 = pojo.getFieldDescription(field).indexOf("endpattern") />
<#assign pattern = pojo.getFieldDescription(field).substring(pos1+8,pos2) />  
    ${field.name}.setInputVerifier(new InputVerifier()
    {
        // ${pojo.getFieldDescription(field)} ${pattern}
        public boolean verify(JComponent input)
        {
        if (!(input instanceof JTextField))
            return true; // give up focus
        Pattern p = Pattern
            .compile("${pattern}");
        Matcher m = p.matcher(((JTextField) input).getText());
        boolean b = m.matches();
        if (b)
        {
            ;// input.set
        }
        return b;
        }
    });
</#if>
		
		
		label_${field.name}.setLabelFor(${field.name});
		pUpper.add(${field.name});
<#assign x = x+1> 	
	</#if>	
	<#if (field.type.toString().indexOf("ManyToOneType") > 0) >
		for (${pojo.beanCapitalize(field.name)} item : data.get${pojo.beanCapitalize(field.name)}s())
		{
			${field.name}ComboBox.addItem(item);
		}
	</#if>
</#if> 
</#foreach>			 

		SpringUtilities.makeCompactGrid(pUpper,
			${x}, 2, //rows, cols
			6, 6,        //initX, initY
			6, 6);       //xPad, yPad

		JPanel pDown = new JPanel();
		pDown.setLayout(new FlowLayout());
		JButton okButton = new JButton(bundle.getString("confirm"));
		JButton cancelButton = new JButton(bundle.getString("cancel"));
		pDown.add(okButton);
		pDown.add(cancelButton);
	
		this.add(pUpper, BorderLayout.NORTH);
		this.add(pDown, BorderLayout.SOUTH);

	okButton.addActionListener(new ActionListener()
	{
		public void actionPerformed(ActionEvent ae)
		{
<#foreach field in pojo.getAllPropertiesIterator()>
<#if !pojo.getJavaTypeName(field,false).equals("Set") >
	<#if pojo.getFieldDescription(field).indexOf("editable") != -1 >
		<#if pojo.getJavaTypeName(field,false).equals("String")>
        if( ${field.name} != null )
			_${pojo.getDeclarationName()}.set${pojo.beanCapitalize(field.name)}(${field.name}.getText());
		</#if>		
		<#if pojo.getJavaTypeName(field,false).equals("Long")>
        if( ${field.name} != null )
			_${pojo.getDeclarationName()}.set${pojo.beanCapitalize(field.name)}(new Long(${field.name}.getText()));
		</#if>		
	</#if>	
</#if> 
</#foreach>			 
			if( _${pojo.getDeclarationName()}.getCreateTime() == null )
			{
			    _${pojo.getDeclarationName()}.setCreateTime(new Date());
			}
			_${pojo.getDeclarationName()}.setModifyTime(new Date());
			data.create${pojo.getDeclarationName()}(_${pojo.getDeclarationName()});
			if (callingPanel != null)
			{
				callingPanel.updateUI();
				//firePropertyChange(arg0, arg1, arg2);
			}
			TopLevel.frame.getGlassPane().setVisible(false);
			TopLevel.frame.getGlassPane().setVisible(false);
		}
	});
	cancelButton.addActionListener(new ActionListener()
	{
		public void actionPerformed(ActionEvent ae)
		{
			TopLevel.frame.getGlassPane().setVisible(false);
		}
	});
    }

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event-dispatching thread.
     */
    private static void createAndShowGUI()
    {
		// Create and set up the window.
		JFrame frame = new JFrame(bundle.getString("${pojo.getDeclarationName()}_management"));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
		// Create and set up the content pane.
		${pojo.getDeclarationName()}AddEdit newContentPane = new ${pojo.getDeclarationName()}AddEdit(null, new ${pojo.getDeclarationName()}());
		newContentPane.setOpaque(true); // content panes must be opaque
		frame.setContentPane(newContentPane);
	
		// Display the window.
		frame.pack();
		frame.setVisible(true);
    }
	
    public static void main(String[] args)
    {
		// Schedule a job for the event-dispatching thread:
		// creating and showing this application's GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable()
		{
			public void run()
			{
				// read from file MessagesBundle_en_us.properties
				bundle = ResourceBundle.getBundle("MessagesBundle", Locale.CHINA);
				//System.out.println("Message in " + Locale.US + ": " + bundle.getString("greeting"));		
				createAndShowGUI();
			}
		});
	}
}